#include "sdl.h"
#include "game.h"

const int MAX_FPS = 250;

bool Game::start()
{
	if (SDL_Init(SDL_INIT_EVERYTHING) > -1)
	{
		// initialize game objects here....
		// NOTE: Should use another if..else statement for
		// failure to initialize objects
		
		/*
			SDL_SetVideoMode -- Set up a video mode with the specified width, height and bits-per-pixel.

			NOTE: Last parameter used to assign different flags...
				SDL_HWSURFACE - Stored in video memory
				SDL_DOUBLEBUF - Double buffered **(Used to reduce flickering of images on screen)**
		*/
		display = SDL_SetVideoMode(X_MAX, Y_MAX, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
		paddle = new Paddle(SDLK_w, SDLK_s, Point(10, 10));
		paddle2 = new Paddle(SDLK_UP, SDLK_DOWN, Point(620, 10));
		ball = new Ball();
		score = new ScoreScreen(paddle, paddle2);


		// failed to load the display
		if (!display)
			return false;

		// failed to load the paddles
		if (!paddle || !paddle2)
			return false;

		// failed to load ball
		if (!ball)
			return false;

		// failed to load score
		if (!score)
			return false;

		// if everything checks out fine...
		return true;
	}
	else
		return false;
}
bool Game::input(SDL_Event* e)
{
	// create an array of the keyboard 
	Uint8 *keystate = SDL_GetKeyState(NULL);

	// filter the input
	switch(e->type)
	{
		case SDL_KEYDOWN:		
			// if we're pressing the "ESC" key, end the game.
			if (keystate[SDLK_ESCAPE])
				return false;
	}

	paddle->input(e);
	paddle2->input(e);
	return true;
}
void Game::update()
{
	// check collisions
	if (ball->location.x <= (paddle->location.x + paddle->width))
		ball->checkCollision(paddle);
	else if (ball->location.x + ball->width >= (paddle2->location.x))
		ball->checkCollision(paddle2);

	if  ((ball->location.y < 0) ||(ball->location.y + ball->height > Y_MAX))
		ball->update(1,-1);

	// update speed and location values
	ball->update(paddle, paddle2);
}

void Game::draw(SDL_Surface* display)
{
	fps1 = SDL_GetTicks();
	// call draw functions for each object
	// perform genereal game draw functions

	SDL_FillRect(display, NULL, 0x000000); // clear the screen

	// draw the paddles
	paddle->draw(display);
	paddle2->draw(display);

	// draw the ball
	ball->draw(display);
	score->draw(display);

	SDL_Flip(display);		// used with double buffering
	fps2 = SDL_GetTicks();


	if ((fps2-fps1) < 1000/MAX_FPS)
		SDL_Delay(1000/MAX_FPS - (fps2-fps1));
}

void Game::end()
{
	// Call clean functions for each object..
	// Release resources for all objects used

	// Quit SDL
	SDL_Quit();
}